package com.magic.himalaya;

import androidx.appcompat.app.AppCompatActivity;
import androidx.viewpager.widget.ViewPager;

import android.animation.ValueAnimator;
import android.os.Bundle;
import android.view.Gravity;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import com.magic.himalaya.R;
import com.magic.himalaya.adapters.TrackImagePagerAdapter;
import com.magic.himalaya.interfaces.IPlayViewCallBack;
import com.magic.himalaya.presenters.PlayerPresenter;
import com.magic.himalaya.utils.Constants;
import com.magic.himalaya.utils.LogUtil;
import com.magic.himalaya.views.PlayerListPopupWindow;
import com.ximalaya.ting.android.opensdk.model.track.Track;
import com.ximalaya.ting.android.opensdk.player.service.XmPlayListControl;

import java.util.Date;
import java.util.List;

public class PlayerActivity extends AppCompatActivity implements IPlayViewCallBack, PlayerListPopupWindow.OnClickPlayerListItemListener {

    private PlayerPresenter mPlayerPresenter;
    private TextView mTitle;
    private TextView mPlayed_time;
    private SeekBar mPlayed_seekbar;
    private TextView mDuration_time;
    private ImageView mPlayMode;
    private ImageView mPlay_pre;
    private ImageView mStart_play;
    private ImageView mStart_next;
    private ImageView mPlayer_list;
    private boolean isCheckedSeekBar = false;
    private ViewPager mImage_pager_view;
    private TrackImagePagerAdapter mPagerAdapter;
    private PlayerListPopupWindow mPlayerListPopupWindow;//播放列表
    private ValueAnimator mValueAnimator;//背景变换动画

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_player);

        //设置系统UI(状态栏隐藏)
//        getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION);
//        getWindow().setStatusBarColor(Color.TRANSPARENT);

        mPlayerPresenter = PlayerPresenter.getInstance();
        initView();
        initEvent();

        mPlayerPresenter.registerViewCallBack(this);
        mPlayerPresenter.playByIndex(mPlayerPresenter.getCurrentIndex()); //获得播放列表并渲染图片集
        //播放器当前播放模式显示
        mPlayerPresenter.initPlayMode();

    }

    private void initEvent() {
        //点击暂停播放按钮时
        mStart_play.setOnClickListener(v -> {
            //检测当前是否在播放
            //如果正在播放的话则将暂停，否则播放
            if (mPlayerPresenter.isPlaying()) {
                mPlayerPresenter.pause();  //暂停播放
            } else {
                mPlayerPresenter.play();  //开始播放
            }
        });

        //拖动进度条进行更改声音播放位置
        mPlayed_seekbar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            //移动拖动条
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                mPlayed_time.setText(Constants.timeFormat.format(new Date(progress * 1000)));
                LogUtil.d("TAG", "1");
            }

            //点击拖动条
            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
                isCheckedSeekBar = true;
                LogUtil.d("TAG", "2");

            }

            //松开拖动条
            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                isCheckedSeekBar = false;
                mPlayerPresenter.seekTo(seekBar.getProgress() * 1000);
                LogUtil.d("TAG", "3::::" + seekBar.getProgress());

            }
        });

        //点击切换上一首
        mPlay_pre.setOnClickListener(v -> mPlayerPresenter.playpre());
        //点击切换下一首
        mStart_next.setOnClickListener(v -> mPlayerPresenter.playnext());

        //点击显示播放列表(PopupWindow窗口)
        mPlayer_list.setOnClickListener(v -> {
            mPlayerListPopupWindow.showAtLocation( v, Gravity.BOTTOM,0,0);
            mPlayerPresenter.playList();//显示播放列表
            //处理一下背景，将背景变暗
            setBgAlpha(0.6f);
        });
        //关闭播放列表(PopupWindow窗口)时,恢复播放器背景颜色
        mPlayerListPopupWindow.setOnDismissListener(() -> setBgAlpha(1.0f));

        //设置滑动图片切歌
        mImage_pager_view.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                //当页面选中的时候，切换播放内容
                mPlayerPresenter.playByIndex(position);
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });

        //切换播放模式
        mPlayMode.setOnClickListener(v -> mPlayerPresenter.switchPlayMode(mPlayerPresenter.getPlayMode()));

        //当播放列表里点击了声音后进行指定位置切歌
        mPlayerListPopupWindow.setOnClickPlayerListItemListener(this);
    }

    /**
     * 设置播放器页面透明度，1.0完全不透明，0.0完全透明
     * @param alpha
     */
    private void setBgAlpha(float alpha) {
        Window window = getWindow();
        WindowManager.LayoutParams windowAttributes = window.getAttributes();
        windowAttributes.alpha = alpha;
        window.setAttributes(windowAttributes);
    }


    private void initView() {

        findViewById(R.id.to_back).setOnClickListener((v) -> finish());//返回按钮

        //===================  获取组件
        //标题
        mTitle = findViewById(R.id.track_title);
        //播放的时间
        mPlayed_time = findViewById(R.id.played_time);
        //进度条
        mPlayed_seekbar = findViewById(R.id.played_seekbar);
        //总时间
        mDuration_time = findViewById(R.id.duration_time);
        //切换播放模式
        mPlayMode = findViewById(R.id.switchPlayMode);
        //上一首
        mPlay_pre = findViewById(R.id.play_next_left);
        //开始/暂停播放按钮
        mStart_play = findViewById(R.id.start_play);
        //下一首
        mStart_next = findViewById(R.id.play_next_right);
        //播放列表
        mPlayer_list = findViewById(R.id.player_list);
        //图片的滑动ViewPager
        mImage_pager_view = findViewById(R.id.track_pager);

        //初始化点进来的数据
        setViewData(mPlayerPresenter.getTrack());//初始化当前播放的数据
        mPagerAdapter = new TrackImagePagerAdapter();
        mImage_pager_view.setAdapter(mPagerAdapter);

        //创建播放列表的布局
        mPlayerListPopupWindow = new PlayerListPopupWindow();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mPlayerPresenter != null) {
            mPlayerPresenter.unRegisterViewCallBack(this);
            mPlayerPresenter = null;
        }
    }

    /**
     * 设置当前正在播放的声音的数据内容渲染
     * @param track
     */
    @Override
    public void setViewData(Track track) {
        //====渲染当前正在播放的声音数据
        mTitle.setText(track.getTrackTitle());//设置标题
        mPlayed_seekbar.setProgress(0);//重置进度条
        mImage_pager_view.setCurrentItem(mPlayerPresenter.getCurrentIndex());//切换图片
        mDuration_time.setText(Constants.timeFormat.format(new Date(track.getDuration() * 1000)));
    }


    //=========================UI回调接口实现

    /**
     * 开始播放图标更改
     */
    @Override
    public void onPlayStart() {
        //开始播放，修改UI层成暂停按钮
        if (mStart_play != null) {
            mStart_play.setImageResource(R.drawable.selector_press_player_pause);
        }
    }

    /**
     * 暂停播放图标更改
     */
    @Override
    public void onPlayPause() {
        if (mStart_play != null) {
            mStart_play.setImageResource(R.drawable.selector_press_player_play);
        }
    }

    /**
     * 停止播放图标更改
     */
    @Override
    public void onPlayStop() {
        if (mStart_play != null) {
            mStart_play.setImageResource(R.drawable.selector_press_player_play);
        }
    }

    /**
     * TODO:播放出错时显示的信息
     */
    @Override
    public void onError() {

    }

    /**
     * 切换下一首图片，和页面内容
     */
    @Override
    public void nextPlay(Track track) {
        setViewData(track);//设置页面内容
    }


    /**
     * 切换上一首图片，和页面内容
     */
    @Override
    public void onPrePlay(Track track) {
        setViewData(track);//设置页面内容
    }

    /**
     * 更新当前播放的时间
     *
     * @param time
     * @param duration
     */
    @Override
    public void onNowPlayTime(int time, int duration) {
        mPlayed_time.setText(Constants.timeFormat.format(new Date(time)));
        if (!isCheckedSeekBar) {
            mPlayed_seekbar.setProgress(time / 1000);
            mPlayed_seekbar.setMax(duration / 1000);
        }
    }

    /**
     * 显示播放列表,渲染播放列表数据
     */
    @Override
    public void onPlayList(List<Track> trackList) {
        mPlayerListPopupWindow.setCurrentPlayerIndex(mPlayerPresenter.getCurrentIndex());//设置播放列表的播放位置
        mPlayerListPopupWindow.addPlayerList(trackList);    //添加播放列表里的声音
    }

    /**
     * 进入播放器会将播放列表图片加载完毕，滑动图片切歌后将标题，进度条都设置成当前的Track内容
     */
    @Override
    public void onListLoaded(List<Track> trackList, int posistion) {
        mPagerAdapter.setData(trackList);//设置播放器图片集
        setViewData(trackList.get(posistion));//渲染当前播放的内容
    }

    /**
     * 改变播放模式的图标
     */
    @Override
    public void onPlayModeChange(XmPlayListControl.PlayMode playMode) {
        switch (playMode) {
            case PLAY_MODEL_SINGLE://单曲播放
                mPlayMode.setImageResource(R.drawable.selector_press_player_status_single);//设置播放器的播放模式图标
                mPlayerListPopupWindow.setPlayerMode(R.drawable.selector_press_player_status_single,"单曲播放");//设置popupwindow(播放列表)里面的播放模式
                break;
            case PLAY_MODEL_SINGLE_LOOP://单曲循环播放
                mPlayMode.setImageResource(R.drawable.selector_press_player_status_single_loop);//设置播放器的播放模式图标
                mPlayerListPopupWindow.setPlayerMode(R.drawable.selector_press_player_status_single_loop,"单曲循环");//设置popupwindow(播放列表)里面的播放模式
                break;
            case PLAY_MODEL_LIST://列表播放
                mPlayMode.setImageResource(R.drawable.selector_press_player_status_list);//设置播放器的播放模式图标
                mPlayerListPopupWindow.setPlayerMode(R.drawable.selector_press_player_status_list,"列表播放");//设置popupwindow(播放列表)里面的播放模式
                break;
            case PLAY_MODEL_LIST_LOOP://列表循环
                mPlayMode.setImageResource(R.drawable.selector_press_player_status_list_loop);//设置播放器的播放模式图标
                mPlayerListPopupWindow.setPlayerMode(R.drawable.selector_press_player_status_list_loop,"列表循环");//设置popupwindow(播放列表)里面的播放模式
                break;
            case PLAY_MODEL_RANDOM://随机播放
                mPlayMode.setImageResource(R.drawable.selector_press_player_status_random);//设置播放器的播放模式图标
                mPlayerListPopupWindow.setPlayerMode(R.drawable.selector_press_player_status_random,"随机播放");//设置popupwindow(播放列表)里面的播放模式
                break;
        }
    }

    /**
     * TODO:广告时间
     */
    @Override
    public void onAdLoading() {

    }

    /**
     * TODO:广告结束后
     */
    @Override
    public void onAFinished() {

    }

    /**
     * 页面提示窗口
     *
     * @param str
     */
    @Override
    public void toast(String str) {
        Toast.makeText(this, str, Toast.LENGTH_SHORT).show();
    }


    /**
     * 在播放器列表切歌时调用
     * @param position
     */
    @Override
    public void switchPlaying(int position) {
        mPlayerPresenter.playByIndex(position);
    }

    /**
     * 在播放器列表切换播放模式调用
     */
    @Override
    public void switchPlayerMode() {
        mPlayerPresenter.switchPlayMode(mPlayerPresenter.getPlayMode());
    }
    //=========================UI回调接口实现 end
}